package net.pulseproject.commons.misc.preferences;

abstract class PreferencesConvertableField<G> extends PreferencesField<G> {

	private final String rawDefaultValue;
	
	private final Converter<G> converter;
	
	public PreferencesConvertableField(final String key, final G defaultValue, final Converter<G> converter) {
		super(key, defaultValue);
		this.converter = converter;
		
		if(defaultValue == null) {
			this.rawDefaultValue = null;
		} else {
			this.rawDefaultValue = this.converter.format(defaultValue);
		}
	}
	
	@Override protected final G getValue(final PreferencesDataAccessor preferencesData) {
		final String rawString = preferencesData.getString(this.getKey(), this.rawDefaultValue);
		
		if(rawString == null) {
			return null;
		}
		
		return this.converter.parse(rawString);
	}

	@Override protected void setValue(final PreferencesDataAccessor preferencesData, final G value) {
		final String rawPosition = this.converter.format(value);
		
		preferencesData.setString(this.getKey(), rawPosition);
	}
}
